package com.zhongjiananbang.plugstartactivitydemo;

import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private Handler mHanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                //先加载
                File file = new File(Environment.getExternalStorageDirectory(), "plugin1.apk");
                if (file.exists()) {
                    PluginManager.getInstance().loadPath(file.getAbsolutePath());
                    Log.d("aa--------", "file:" + file.exists() + "  file:" + file.length() + " file.getAbsolutePath():" + file.getAbsolutePath());
                    //再跳转
                    Intent intent = new Intent(MainActivity.this, ProxyActivity.class);
                    Log.d("aa---", " PluginManager.getInstance().getEntryActivityName():" + PluginManager.getInstance().getEntryActivityName());
                    intent.putExtra("className", PluginManager.getInstance().getEntryActivityName());
                    startActivity(intent);
                } else {
                    Toast.makeText(MainActivity.this, "apk不存在", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PluginManager.getInstance().setContext(this);
    }

    public static class FileUtils {
        private String path = Environment.getExternalStorageDirectory().toString();

        public FileUtils() {
            File file = new File(path);
            /**
             *如果文件夹不存在就创建
             */
            if (!file.exists()) {
                file.mkdirs();
            }
        }

        /**
         * 创建一个文件
         *
         * @param FileName 文件名
         * @return
         */
        public File createFile(String FileName) {
            return new File(path, FileName);
        }
    }

    /**
     * 从服务器下载文件
     *
     * @param path     下载文件的地址
     * @param FileName 文件名字
     */
    public void downLoad(final String path, final String FileName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setReadTimeout(5000);
                    con.setConnectTimeout(5000);
                    con.setRequestProperty("Charset", "UTF-8");
                    con.setRequestMethod("GET");
//                    if (con.getResponseCode() == 200) {
                        InputStream is = con.getInputStream();//获取输入流
                        FileOutputStream fileOutputStream = null;//文件输出流
                        if (is != null) {
                            FileUtils fileUtils = new FileUtils();
                            fileOutputStream = new FileOutputStream(fileUtils.createFile(FileName));//指定文件保存路径，代码看下一步
                            byte[] buf = new byte[1024];
                            int ch;
                            while ((ch = is.read(buf)) != -1) {
                                fileOutputStream.write(buf, 0, ch);//将获取到的流写入文件中
                                fileOutputStream.flush();
                            }
                        }
                        if (fileOutputStream != null) {
                            fileOutputStream.close();
                        }
//                    }
                    mHanlder.sendEmptyMessage(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //跳转
    public void start(View view) {
        //先加载
        File file = new File(Environment.getExternalStorageDirectory(), "plugin1.apk");
        if (file.exists()) {
             PluginManager.getInstance().loadPath(file.getAbsolutePath());
            Log.d("aa--------", "file:" + file.exists() + "  file:" + file.length() + " file.getAbsolutePath():" + file.getAbsolutePath());
            //再跳转
            Intent intent = new Intent(this, ProxyActivity.class);
            Log.d("aa---", " PluginManager.getInstance().getEntryActivityName():" + PluginManager.getInstance().getEntryActivityName());
            intent.putExtra("className", PluginManager.getInstance().getEntryActivityName());
            startActivity(intent);
        } else {
            downLoad("http://47.94.149.111/caring_interface/upload/data/plugin1.apk", "plugin1.apk");//下载完成后就可以在手机目录里查看到了
        }

    }

}
